package com.zui.manager;


import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.zui.entity.BaseEntity;
import com.zui.entity.product.Geo;
import com.zui.entity.setup.Ip;

@SuppressWarnings({"unchecked","rawtypes"})
@Transactional
public class GeoManagerImpl extends EntityManagerImpl<Geo, Long> implements
		GeoManager {
	@Autowired
	private SessionManager sessionManager;
	
	/**
	 * 
	 */
	@Transactional(readOnly = true)
	public List<Geo> findGeosByGeoTypeId(String id){
		if (id == null)
			return null;
		DetachedCriteria criteria = DetachedCriteria.forClass(Geo.class);
		criteria.add(Restrictions.eq("geoType.id", id));
		criteria.add(Restrictions.or(Restrictions.isNull("isDeleted"), Restrictions.eq("isDeleted",BaseEntity.FLAG_N)));

		criteria.addOrder(Order.asc("id"));
		return sessionManager.findByCriteria(criteria);

	}
	/**
	 * 
	 */
	@Transactional(readOnly = true)
	public Geo findGeoByIp(String ip){
		
		if (ip == null)
			return this.loadById(Geo.DEFAULT_CITY_ID);
		
		Geo geo = null;
		String[] values = ip.split("\\.");
		Long ipLong = new Long(values[0]).longValue() *256*256*256
				+ new Long(values[1]).longValue() *256*256
				+ new Long(values[2]).longValue() *256
				+ new Long(values[3]).longValue();
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Ip.class);
		criteria.add(Restrictions.le("startIp", ipLong));
		criteria.add(Restrictions.ge("endIp", ipLong));
		List ips = sessionManager.findByCriteria(criteria);
		if (ips != null && !ips.isEmpty())
			geo = ((Ip)ips.get(0)).getGeo();
		
		return geo==null ? loadById(Geo.DEFAULT_CITY_ID) : geo;
			

	}
}
